package cn.template.config;

import cn.template.models.common.CustomErrorResponse;
import cn.template.models.exceptions.AppException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

// to handle all exceptions, the basePackages must set up properly
@RestControllerAdvice(basePackages = "cn.template.controllers")
public class RestControllerErrorHandler {

    @ExceptionHandler(AppException.class)
    public ResponseEntity<CustomErrorResponse> handleNotFoundError(HttpServletRequest request, AppException ex) {
        return new ResponseEntity<>(new CustomErrorResponse(request, ex), ex.getStatus());
    }

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<CustomErrorResponse> handleCommonError(HttpServletRequest request, RuntimeException ex) {
        return new ResponseEntity<>(new CustomErrorResponse(request, ex.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
